const fs = require("fs");
const path = require("path");
const colors = require("colors-console");
// const { exec } = require('child_process')
// const package = require("./package.json");
// console.log('--package--',package);

// 解析json文件
function getJsonFileData(jsonFilePath, jsonFileName) {
  if (!fs.existsSync(jsonFilePath)) {
    throw new Error(jsonFilePath + " 不存在");
  }
  try {
    return JSON.parse(fs.readFileSync(jsonFilePath, "utf8"));
  } catch (e) {
    console.error(jsonFileName + " 解析失败");
  }
}

// 修改json文件
function modifyJsonFileData(filePath, fileName, params) {
  // 1. 解析文件
  let json = "";
  try {
    console.log(fileName, "--filePath--", filePath);
    json = getJsonFileData(filePath, fileName);
  } catch (error) {
    console.log("--error--", error);
    return false;
  }
  // 2. 配置文件参数
  json = { ...json, ...params };
  // 3. manifest.json写入参数
  const jsonStr = JSON.stringify(json, "", 2) + "\r\n";
  try {
    fs.writeFileSync(jsonFilePath, jsonStr);
    console.log(colors("green", `${jsonFileName} modified success \r\n`));
    return true;
  } catch (e) {
    console.log(colors("red", `${jsonFileName} modified failed \r\n`));
    return false;
  }
}

// 1. 校验参数
const argv = process.argv;
if (argv.length <= 2) {
  console.log(colors("yellow", "Warning") + " ---> " + "脚本：无参数");
} else {
  const envStr = argv[2];
  // 2.1 运行环境
  const env = envStr.split(":")[0] || "dev";
  // 2.2 运行平台
  const platform = envStr.split(":")[1];
  console.log("当前运行环境：" + colors("green", env) + "\n");
  console.log("当前运行平台：" + colors("green", platform) + "\n");
}

const jsonFileName = "package.json";
const jsonFilePath = path.resolve(process.env.INIT_CWD, jsonFileName);
const date = new Date();
const nowDate = `${date.getFullYear()}-${
  date.getMonth() + 1
}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;

modifyJsonFileData(jsonFilePath, jsonFileName, { versionTime: nowDate });
